package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {
    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> listAll() {
        return bannerRepository.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.ASC,"_id");
        return DBHelper.query(mongoTemplate,query,Banner.class,pageable);
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        if (StringUtils.hasLength(banner.getId())){
            this.update(banner);
        }else {
            this.save(banner);
        }
    }

    @Override
    public List<Banner> getTravelBannerTop5() {
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        List<Banner> list = bannerRepository.findByStateAndType(Banner.STATE_NORMAL, Banner.TYPE_TRAVEL,pageable);
        return list;
    }

    @Override
    public List<Banner> getStrategyBannerTop1() {
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        List<Banner> list = bannerRepository.findByStateAndType(Banner.STATE_NORMAL, Banner.TYPE_STRATEGY,pageable);
        return list;
    }
}
